#define _CRT_SECURE_NO_WARNINGS 1

#include"string.h"

namespace yyh
{
	const size_t string::npos = -1;

	string::string(const char* str)
		:_size(strlen(str))
	{
		_str = new char[_size + 1];
		_capacity = _size;
		strcpy(_str, str);
	}

	string::~string()
	{
		delete[] _str;
		_str = nullptr;
		_size = _capacity = 0;
	}

	void string::reserve(size_t n)
	{
		if (n > _capacity)
		{
			char* temp = new char[n + 1];
			strcpy(temp, _str);
			delete[] _str;
			_str = temp;
			_capacity = n;
		}
	}

	void string::push_back(char ch)
	{
		if (_size == _capacity)
		{
			reserve(_capacity == 0 ? 4 : 2 * _capacity);
		}
		_str[_size++] = ch;
		_str[_size] = '\0';
	}

	void string::append(const char* str)
	{
		size_t len = strlen(str);
		if (_size + len > _capacity)
		{
			size_t NewCapacity = 2 * _capacity;
			if (_size + len > NewCapacity)
			{
				NewCapacity = _size + len;
			}
			reserve(NewCapacity);
		}
		strcpy(_str + _size, str);
		_size += len;
	}

	string& string::operator +=(char ch)
	{
		push_back(ch);
		return *this;
	}

	string& string::operator +=(const char* str)
	{
		append(str);
		return *this;
	}

	void test1()
	{
		string s1;
		cout << s1.c_str() << endl;
		string s2("hello world");
		cout << s2.c_str() << endl;
		s2 += 'y';
		s2 += "yyh";
		s2 += "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
		cout << s2.c_str() << endl;
	}
}